package com.moody.service.impl;

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.moody.hibernate.dao.DebtInfoDAO;
import com.moody.hibernate.dao.PdHDAO;
import com.moody.hibernate.domain.CustInfo;
import com.moody.hibernate.domain.DebtInfo;
import com.moody.hibernate.domain.OrgInfo;
import com.moody.hibernate.domain.PdH;
import com.moody.hibernate.domain.ReportList;
import com.moody.hibernate.domain.RiskReportIRDetail;
import com.moody.hibernate.domain.RiskReportREDetail;
import com.moody.service.CustomerService;
import com.moody.service.RiskReportService;
import com.moody.service.SystemService;

/*
 * Copyright ? Moody analytics   
 *
 * @Title: RiskReportServiceImpl.java 
 * @Package： com.moody.service.impl 
 * @author： Liu Peng
 * @Description: 风险报告功能实现   
 * @date： 2012-2-29 上午11:34:46
 * @Modified by: Liu Peng 
 * @version V1.0   
 */
@SuppressWarnings("unchecked")
@Service
public class RiskReportServiceImpl implements RiskReportService{
	private static final Logger log = LoggerFactory.getLogger(RiskAppServiceImpl.class);
	WebApplicationContext web = ContextLoader.getCurrentWebApplicationContext();
	ServletContext context = web.getServletContext();  
	WebApplicationContext ctx  = WebApplicationContextUtils.getWebApplicationContext(context);
	
	
	Map<String, List<String>> orgMap = (Map<String, List<String>>)context.getAttribute("OrgMap");
	
	private PdHDAO pdHDAO = PdHDAO.getFromApplicationContext(ctx);
	private DebtInfoDAO debtInfoDAO = DebtInfoDAO.getFromApplicationContext(ctx);

	LinkedList<ArrayList<String>> resultListOfIRDetail = new LinkedList<ArrayList<String>>();
	LinkedList<ArrayList<String>> resultListOfREDetail = new LinkedList<ArrayList<String>>();
	@Resource
	private CustomerService customerService;
	@Resource
	private SystemService systemService;

	
	/**
	 * 根据检索条件获得非零售客户内部评级结果（非零售内部评级明细表）
	 */
	public List<RiskReportIRDetail> getIRDetailByCondition(String queryCustType2,String date,String orgId,String userId,String logonUserId,String logonOrgId){
		List<RiskReportIRDetail> list = pdHDAO.findIRDetailByCondition(queryCustType2, date, orgId, userId);
		List<String> subOrgList = orgMap.get(logonOrgId);
		Iterator<RiskReportIRDetail> it = list.iterator();
		while(it.hasNext()){
			RiskReportIRDetail item = it.next();
			CustInfo cust = customerService.findCustByCustId(item.getCustID());
			if(!cust.getInputUserId().equals(logonUserId) && !subOrgList.contains(cust.getInputOrgId())) it.remove();
			else{
				if(item.getConfirmOrgID() != null){
					OrgInfo org = systemService.findOrgById(item.getConfirmOrgID());
					if(org != null) item.setConfirmOrgID(org.getOrgname());
				}
				if(item.getFirstOrgID() != null){
					OrgInfo org = systemService.findOrgById(item.getFirstOrgID());
					if(org != null) item.setFirstOrgID(org.getOrgname());
				}
			}
			
		}
		return list;
	}
	
	/**
	 *  根据检索条件获得非零售客户风险暴露结果（非零售风险暴露明细表）
	 */
	public List<RiskReportREDetail> getREDetailByCondition(String queryCustType2,String date,String orgId,String userId,String currency,String logonUserId,String logonOrgId){
		List<RiskReportREDetail> list = debtInfoDAO.findREDetailByCondition(queryCustType2, date, orgId, userId,currency);
		List<String> subOrgList = orgMap.get(logonOrgId);
		Iterator<RiskReportREDetail> it = list.iterator();
		while(it.hasNext()){
			RiskReportREDetail item = it.next();
			CustInfo cust = customerService.findCustByCustId(item.getCustID());
			if(!cust.getInputUserId().equals(logonUserId) && !subOrgList.contains(cust.getInputOrgId())) it.remove();
			else{
				item.setOperator(systemService.findUserById(cust.getInputUserId()).getUsername());
			}
		}
		return list;
	}
	
	
//	/**
//	 * 获得每个非零售客户最新一期的内部评级结果
//	 */
//	@SuppressWarnings("unchecked")
//	public List<ArrayList<String>> getIRDetail() {
//		List<PdH> pdHList = new LinkedList<PdH>();
//		PdH tempPdH = null;
//		PdH endFlagPdH = new PdH("endFlag");
//		endFlagPdH.setCustId("endFlag");
//		resultListOfIRDetail.clear();
//		
//		pdHList = pdHDAO.findAll();
//		if(pdHList.size() == 0) return null; 
//		pdHList.add(endFlagPdH);
//		tempPdH = pdHList.get(0); //此时，tempPdH != endFlagPdH，因为size != 0
//		for(PdH pdH : pdHList){
//			if("endFlag".equals(pdH.getSerialNo())){
//			// 若到达结尾:
//				if(tempPdH.getCustId() == null 
//						|| customerService.findCustByCustId(tempPdH.getCustId()) == null 
//						|| tempPdH.getConfirmDate() == null 
//						|| customerService.findCustByCustId(tempPdH.getCustId()).getCustType().equals("04")){
//					//验证tempPdH的合理性：不存在CustId、不存在对应的Cust、无评级日期、零售客户等都表明不合理。（其实，若tempPdH被替换过，则必是合理的）
//					break;
//				}
//				else{//合理时，添加该条目
//					addResultListOfIRDetail(tempPdH);
//				}
//				break;
//			}
//			
//			// 若未达到结尾
//			// 验证数据有效性:
//			// 1. 测试阶段，数据库数据存在错误，需排除CustId对应的客户不存在的情况
//			if(pdH.getCustId() == null || customerService.findCustByCustId(pdH.getCustId()) == null) continue;
//			// 2. 若客户为零售客户，则取下一条
//			if(customerService.findCustByCustId(pdH.getCustId()).getCustType().equals("04")) continue;
//			
//			// 对有效数据的操作
//			if(!tempPdH.getCustId().equals(pdH.getCustId())){
//				//若客户ID不同，则将上一个客户的最新评级结果存入list
//				addResultListOfIRDetail(tempPdH);
//				tempPdH = pdH;
//			}
//			else{
//				//若客户ID相同，则当前的评级结果（tempPdH）为两者中最新的记录，最新指评级认定时间最晚
//				if(isLater(pdH,tempPdH))
//					tempPdH = pdH;
//			}
//		}
//		return resultListOfIRDetail;
//	}
//	/**
//	 * 获得每个非零售客户最新一期的内部评级表头
//	 */
//	public ArrayList<String> getIRDetailTitle(){
//		ArrayList<String> titleOfIRDetail = new ArrayList<String>();
//		RiskReportIRDetail obj = new RiskReportIRDetail();
//		Field[] fields = obj.getClass().getDeclaredFields();
//		for(int i = 1; i < fields.length ; i++){
//			if(fields[i].getName().length() > 5 && "nameOf".equals(fields[i].getName().substring(0, 6))){
//				try {
//					fields[i].setAccessible(true);
//					titleOfIRDetail.add(fields[i].get(obj).toString());
//				} catch (IllegalArgumentException e) {
//					// 
//					e.printStackTrace();
//				} catch (IllegalAccessException e) {
//					// 
//					e.printStackTrace();
//				}
//			}	
//		}
//		return titleOfIRDetail;
//	}
//	/**
//	 * 根据参数的线索，获取表行的所有数据，作为一行插入到结果列表中
//	 * @param pdH
//	 * @return
//	 */
//	private boolean addResultListOfIRDetail(PdH pdH){
//		ArrayList<String> IRDetailData = new ArrayList<String>();
//		if(pdH == null || pdH.getSerialNo().equals("endFlag"))return false;
//		CustInfo custInfo = customerService.findCustByCustId(pdH.getCustId());
//		if(custInfo == null) return false;
//		
//		//根据pdH信息填充IRBDetail表格所有信息
//		RiskReportIRDetail IRDetail = new RiskReportIRDetail();
//		if(resultListOfIRDetail != null)IRDetail.setNo("" + (resultListOfIRDetail.size() + 1));
//		else IRDetail.setNo("1");
//		IRDetail.setArea(null);
//		IRDetail.setConfirmDate(pdH.getConfirmDate());
//		IRDetail.setConfirmOrgID(pdH.getConfirmOrgId());
//		IRDetail.setCreditTime(null);
//		IRDetail.setCustID(pdH.getCustId());
//		IRDetail.setCustName(custInfo.getCustName());
//		IRDetail.setCustScope(custInfo.getCustScope());
//		IRDetail.setCustType(custInfo.getCustType());
//		IRDetail.setExposureType(custInfo.getExposureType());
//		IRDetail.setFirstOrgID(pdH.getFirstOrgId());
//		IRDetail.setIndustryType(custInfo.getIndustryType());
//		IRDetail.setNewestPD(pdH.getConfirmPdlevel());
//		IRDetail.setNewestPDReportNo(null);
//		IRDetail.setOrgType(custInfo.getOrgType());
//		
//		//将IRDetail表格对象的属性值按顺序转存入链表中
//		Field[] fields = IRDetail.getClass().getDeclaredFields();
//		String prefix = null;
//		for(int i = 1; i < fields.length ; i++){
//			if(fields[i].getName().length() > 6) prefix = fields[i].getName().substring(0, 6);
//			if(prefix != null && prefix.equals("nameOf")) {
//				prefix = null;
//				continue;
//			}
//			
//			try {
//				fields[i].setAccessible(true);//反射机制获取私有属性时，首先需更改访问权限
//				if(fields[i].get(IRDetail) == null) IRDetailData.add("");
//				else IRDetailData.add(fields[i].get(IRDetail).toString());
//			} catch (IllegalArgumentException e) {
//				// 
//				e.printStackTrace();
//			} catch (IllegalAccessException e) {
//				// 
//				e.printStackTrace();
//			}
//		}
//		resultListOfIRDetail.add(IRDetailData);
//		return true;
//	}
//	/**
//	 * 判定参数哪一个更近
//	 * @param pdH1
//	 * @param pdH2
//	 * @return 如果 pdH1 isLater than pdH2，返回 true
//	 */
//	private boolean isLater(PdH pdH1,PdH pdH2){
//		if(pdH1 == null || pdH1.getConfirmDate() == null) return false;
//		if(pdH2 == null || pdH2.getConfirmDate() == null) return true;
//		
//		DateFormat df = DateFormat.getDateInstance();
//		Date date1,date2;
//		try {
//			date1 = df.parse(pdH1.getConfirmDate());
//		} catch (ParseException e) {
//			e.printStackTrace();
//			return false;
//		}
//		try {
//			date2 = df.parse(pdH2.getConfirmDate());
//		} catch (ParseException e) {
//			e.printStackTrace();
//			return true;
//		}
//		if(date1.after(date2)) return true;
//		else return false;
//		
//	}
	
	/**
	 * 根据债项编号获得风险暴露明细表
	 */
	@SuppressWarnings("unchecked")
	public List<ArrayList<String>> getREDetail() {
		List<DebtInfo> debtInfoList = new LinkedList<DebtInfo>();
		resultListOfREDetail.clear();
		
		debtInfoList = debtInfoDAO.findAll();
		for(DebtInfo debtInfo : debtInfoList){
			//若客户为零售客户，则取下一条
			CustInfo custInfo = customerService.findCustByCustId(debtInfo.getCustId());
			if(custInfo == null || custInfo.getCustType().equals("04")) continue;
			addResultListOfREDetail(debtInfo);
		}
		sortResultListOfREDetail();
		return resultListOfREDetail;
	}
	/**
	 * 获得风险暴露明细表标头名称
	 */
	public ArrayList<String> getREDetailTitle() {
		ArrayList<String> titleOfREDetail = new ArrayList<String>();
		RiskReportREDetail obj = new RiskReportREDetail();
		Field[] fields = obj.getClass().getDeclaredFields();
		for(int i = 1; i < fields.length ; i++){
			if(fields[i].getName().length() > 5 && "nameOf".equals(fields[i].getName().substring(0, 6))){
				try {
					fields[i].setAccessible(true);
					titleOfREDetail.add(fields[i].get(obj).toString());
				} catch (IllegalArgumentException e) {
					// 
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// 
					e.printStackTrace();
				}
			}	
		}
		return titleOfREDetail;
	}
	/**
	 * 根据参数的线索，获取表行的所有数据，作为一行插入到结果列表中
	 * @param debtInfo
	 * @return
	 */
	public boolean addResultListOfREDetail(DebtInfo debtInfo){
		RiskReportREDetail REDetail = new RiskReportREDetail();
		ArrayList<String> REDetailData = new ArrayList<String>();
		CustInfo custInfo = customerService.findCustByCustId(debtInfo.getCustId());
		
		if(debtInfo == null) return false;
		
		REDetail.setArea(null);
		REDetail.setCustID(debtInfo.getCustId());
		REDetail.setCustName(custInfo.getCustName());
		if(debtInfo.getDebtBalance() != null) REDetail.setDebtBalance("" + debtInfo.getDebtBalance());
		else REDetail.setDebtBalance("");
		REDetail.setDebtNo(debtInfo.getDebtNo());
		REDetail.setDebtType(debtInfo.getDebtType());
		REDetail.setExposureType(custInfo.getExposureType());
		REDetail.setIndustryType(custInfo.getIndustryType());
		REDetail.setOperator(null);
		REDetail.setSystemPDLevel(null);
		
		//将REDetail表格对象的属性值按顺序转存入链表中
		Field[] fields = REDetail.getClass().getDeclaredFields();
		String prefix = null;
		for(int i = 1; i < fields.length ; i++){
			//过滤
			if(fields[i].getName().length() > 6) prefix = fields[i].getName().substring(0, 6);
			if(prefix != null && prefix.equals("nameOf")) {
				prefix = null;
				continue;
			}
			
			try {
				fields[i].setAccessible(true);//反射机制获取私有属性时，首先需更改访问权限
				if(fields[i].get(REDetail) == null) REDetailData.add("");
				else REDetailData.add(fields[i].get(REDetail).toString());
			} catch (IllegalArgumentException e) {
				// 
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// 
				e.printStackTrace();
			}
		}
		resultListOfREDetail.add(REDetailData);
		return true;
		
	}
	/**
	 * 按照XXX要求讲结果排序
	 */
	public void sortResultListOfREDetail(){
		//TODO 
	
	}
	
}
